package lainey.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import lainey.ui.dialog.LoadingDialog;
import lainey.ui.utils.LogUtil;
import lainey.ui.utils.NetworkUtil;
import lainey.ui.utils.ThreadPoolManager;

public class BaseAppCompatActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "BaseAppCompatActivity";

    private LoadingDialog mLoadingDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestPermission();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    /**
     * 设置沉浸状态栏
     */
    public void setImmerseStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    public void showLoadingDialogOnUi() {
        showLoadingDialogOnUi(null);
    }

    public void showLoadingDialogOnUi(int resId) {
        String text = getString(resId);
        showLoadingDialogOnUi(text);
    }

    public void showLoadingDialogOnUi(final String message) {
        runOnUi(
                () -> {
                    try {
                        getLoadingDialog(message);
                        mLoadingDialog.show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
        );
    }

    public void dismissLoadingDialogOnUi() {
        runOnUi(
                () -> {
                    try {
                        if (mLoadingDialog != null) {
                            mLoadingDialog.dismiss();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
        );
    }

    public LoadingDialog getLoadingDialog(String message) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(this, message);
        } else {
            mLoadingDialog.setMessage(message);
        }
        return mLoadingDialog;
    }

    public void setLoadingDialogMessage(String message) {
        if (mLoadingDialog != null) {
            mLoadingDialog.setMessage(message);
        }
    }

    public void showToastOnUi(int resId) {
        String str = getString(resId);
        showToastOnUi(str);
    }

    public void showToastOnUi(final String msg) {
        runOnUiThread(
                () -> showToast(msg)
        );
    }

    public void showToast(int resId) {
        Toast.makeText(this, resId, Toast.LENGTH_SHORT).show();
    }

    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public void runOnUi(Runnable run) {
        runOnUiThread(run);
    }

    public void hideSoftInput(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void executeTask(Runnable run) {
        boolean connected = NetworkUtil.isNetworkConnected(this);
        if (connected) {
            ThreadPoolManager.executeInCachePool(run);
        } else {
            onNetworkError();
        }
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 网络未连接回调
     */
    public void onNetworkError() {
        dismissLoadingDialogOnUi();
        showToastOnUi(R.string.ui_hint_network);
    }

    public void openActivity(Class clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    ////////////////////////////////////////权限相关//////////////////////////////
    public static final int REQUEST_CODE_PERMISSION = 666;
    public static final int REQUEST_CODE_PERMISSION_OVERLAY = 667;

    private String[] permissions = {
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,

    };

    private void requestPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return;
        // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
        for (String permission : permissions) {
            int result = ContextCompat.checkSelfPermission(this, permission); // 检查该权限是否已经获取
            LogUtil.d(TAG, permission + ":" + result);
            if (result != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_PERMISSION);
            }
        }
    }

    public void showSystemWindowDialog(String packageName) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return;
        boolean canDrawOverlays = Settings.canDrawOverlays(this);
        if (canDrawOverlays) return;
        new AlertDialog.Builder(this)
                .setTitle(R.string.ui_permission_overlay)
                .setMessage(R.string.ui_permission_overlay_hint)
                .setNegativeButton(R.string.ui_cancel, (dialog, which) -> {
                            dialog.dismiss();
                        }
                )
                .setPositiveButton(R.string.ui_agree, (dialog, which) -> {
                            dialog.dismiss();
                            requestPermissionForSystemWindow(packageName);
                        }
                )
                .setCancelable(false)
                .show();
    }

    /**
     * 请求用户给予悬浮窗的权限
     */
    public void requestPermissionForSystemWindow(String packageName) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return;
        Uri uri = Uri.parse("package:" + packageName);
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, uri);
        startActivityForResult(intent, REQUEST_CODE_PERMISSION_OVERLAY);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    LogUtil.d(TAG, "权限允许");
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                } else {
                    LogUtil.d(TAG, "权限拒绝");
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                break;
            case REQUEST_CODE_PERMISSION_OVERLAY:
                break;
        }
    }


}
